package com.jlnk.rxjavademo.presenter;

import com.jlnk.rxjavademo.service.ApiService;
import com.jlnk.rxjavademo.entity.ImageEntity;
import com.jlnk.rxjavademo.client.RetrofitClient;
import java.util.List;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class MainPresenter {
    private MainView mainView;
    private ApiService apiService;
    private CompositeDisposable compositeDisposable;

    public MainPresenter(MainView mainView) {
        this.mainView = mainView;
        apiService = RetrofitClient.getClient("https://peapix.com/bing/").create(ApiService.class);
        compositeDisposable = new CompositeDisposable();
    }
    public void loadImageData() {
        mainView.showLoading();
        compositeDisposable.add(apiService.getImageData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::updateList,
                        throwable -> {
                            mainView.showError(throwable.getMessage());
                            mainView.hideLoading();
                        }));
    }
    private void updateList(List<ImageEntity> imageDataList) {
        mainView.updateList(imageDataList);
        mainView.hideLoading();
    }

    public interface MainView {
        void showLoading();
        void hideLoading();
        void showError(String message);
        void updateList(List<ImageEntity> imageDataList);
    }
}